<template>
  <div class="BankAnalysis-container">
    <!-- 栅格 输入框 和按钮 -->
    <el-row class="filterCondition">
      <el-form
        label-width="82px"
        label-position="right"
        ref="formLabelAlign"
        :model="formLabelAlign"
      >
        <!-- <el-form-item  label="城市" v-if="ShowCity"> -->
        <el-form-item label="维度">
          <el-select v-model="formLabelAlign.Dimension" placeholder="放款额">
            <!-- <el-option label="所有" value="all"></el-option> -->
            <el-option
              v-for="item in DimensionList"
              :key="item.id"
              :label="item.name"
              :value="item.name"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="city" label="城市" v-if="ShowCity">
          <el-select v-model="formLabelAlign.city" placeholder="请选择城市">
            <el-option label="所有" value></el-option>
            <el-option
              v-for="item in cityselectList"
              :key="item.id"
              :label="item.name"
              :value="item.name"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item prop="scopeOf" label="层级">
          <el-select v-model="formLabelAlign.scopeOf" placeholder="请选择层级">
            <el-option label="忽略层级" value></el-option>
            <el-option label="城市" value="city" v-if="ShowCity"></el-option>
            <el-option
              v-for="item in cengJiList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>-->
        <el-form-item prop="timeType" label="时间">
          <el-select
            v-model="formLabelAlign.dayType"
            id="time"
            @change="holderQuJian"
            placeholder="时间(默认不限时间)"
          >
            <!-- <el-option label="不限时间" value></el-option> -->
            <el-option v-for="item in timeList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="value1" label="时间区间" v-show="isShow">
          <div class="block">
            <el-date-picker
              v-model="value1"
              type="daterange"
              format="yyyy/MM/dd"
              value-format="yyyy/MM/dd"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </div>
        </el-form-item>
        <el-form-item class="BTN">
          <el-button
            style="background-color:#c73e3a;color:#fff"
            @click="checkCus"
            class="check"
            :disabled="disTBN"
          >查询</el-button>
          <!-- <el-button style="background-color:	#00CDCD;color:#fff" @click="resetForm('formLabelAlign')"   class="check">重置筛选条件</el-button> -->
        </el-form-item>
      </el-form>
    </el-row>
    <!-- Ecahrts -->
    <el-row class="filterCondition" v-loading="loading">
      <h3> 进件银行名称及其所占比重</h3>
      <div id="main" style="width: 100%;height: 530px;" v-if="isShowEchart"></div>
      <h4 v-if="!isShowEchart" style="text-align:center">抱歉！数据过少，不显示图表</h4>
    </el-row>
    <!-- table -->
    <!-- <el-table  @selection-change="changeCus" :row-class-name="tableRowClassName" :data="tableData" style="width: 100%" stripe> -->
    <el-table :data="tableData" v-loading="loading" style="width: 100%" stripe>
      <!-- <el-table-column type="selection" width="55"></el-table-column> -->
      <el-table-column type="index" label="序号" :width="screenWidth/8">
        <template slot-scope="scope">{{(scope.$index)?scope.$index:"-"}}</template>
      </el-table-column>
      <el-table-column prop="bankName" label="金融机构" :width="screenWidth/8"></el-table-column>
      <el-table-column sortable prop="fangKuangRate" label="放款额" :width="screenWidth/8"></el-table-column>
      <el-table-column label="放款额占比" :width="screenWidth/8">
        <template slot-scope="scope">{{ scope.row.fangKuangZBRate |Proportion}}</template>
      </el-table-column>
      <el-table-column sortable prop="fangKuanCount" label="放款笔数" :width="screenWidth/8"></el-table-column>
      <el-table-column label="放款笔数占比" :width="screenWidth/8">
        <template slot-scope="scope">{{ scope.row.fangkuanCountZB|Proportion }}</template>
      </el-table-column>
      <el-table-column sortable prop="thePayeeRate" label="创收数" :width="screenWidth/8"></el-table-column>
      <el-table-column label="创收占比" :width="screenWidth/8">
        <template slot-scope="scope">{{ scope.row.thePayeeZBRate|Proportion }}</template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <!-- <el-pagination  @size-change="handleSizeChange"  @current-change="handleCurrentChange"  :current-page="pageConfig.currentPage"  :page-sizes="[10, 20 ,50, 100]"  :page-size="10"  layout="total, sizes, prev, pager, next, jumper"  :total="pageConfig.total">
    </el-pagination>-->
  </div>
</template>

<script>
// 导入时间戳
import moment from "moment";
import echarts from "echarts";
export default {
  name: "BankAnalysis",
  // 数据
  data() {
    return {
      currentUser: {
        currentName: "",
        currentId: "",
        currentLevel: "",
        currentPhone: "",
        currentcity: ""
      },
      isShowEchart: true,
      ShowCity: false,
      currentUser: {
        currentName: "",
        currentId: "",
        currentLevel: "",
        currentPhone: ""
      },
      loading: true,
      showTimeKind: true,
      //未分割的完整版时间区间
      value1: "",
      //时间区间隐藏状态
      isShow: false,
      //禁用按钮的状态值
      disTBN: false,
      //页码参数
      pageConfig: {
        currentPage: 1, //当前页
        pageSize: 10, //当前单页数据条数
        total: 0 //请求到的数据总条数
      },
      cityselectList: [{ id: 0, name: "请先选择城市" }],
      DimensionList: [
        { id: 1, name: "放款额" },
        { id: 2, name: "放款笔数" },
        { id: 3, name: "创收" }
      ],
      cengJiList: [
        { id: "fenGS", name: "分公司" },
        { id: "quyu", name: "大区" },
        { id: "bumen", name: "部门" },
        { id: "guwen", name: "顾问" }
      ],
      //时间选择生成内容
      timeList: [
        { id: "all", name: "不限时间" },
        { id: "today", name: "今日" },
        { id: "yestoday", name: "昨日" },
        { id: "sevenDay", name: "最近七天" },
        { id: "tomonth", name: "本月" },
        { id: "yesmonth", name: "上月" },
        { id: "customize", name: "自定义" }
      ],
      //客户筛选区域数据
      formLabelAlign: {
        Dimension: "放款额", //维度
        scopeOf: "", //	层级
        city: "上海", //	状态
        timeType: "", //时间类型
        dayType: "tomonth",
        beginTime: moment(new Date()).format("YYYY-MM-01"), //开始时间
        endTime: moment(new Date()).format("YYYY-MM-DD"), //	结束时间
        value1: "", //	结束时间
        pageSize: "", //分页大小
        currentPage: "" //	当前页码
      },
      // 表格依赖于数据没有数据  会一行都没有
      tableData: [],
      //echarts
      charts: "",
      Echartsdata: [
        "中国银行",
        "农业银行",
        "工商银行",
        "建设银行",
        "上海银行",
        "南京银行",
        "光大银行",
        "渣打银行",
        "花旗银行",
        "招商银行",
        "中原银行",
        "广发银行",
        "摩根银行",
        "北京银行",
        "合众银行",
        "光明银行",
        "汇丰银行",
        "五河银行",
        "平安银行"
      ],
      initEchartListdata: [
        { value: 335, name: "中国银行" },
        { value: 310, name: "农业银行" },
        { value: 234, name: "工商银行" },
        { value: 135, name: "建设银行" },
        { value: 1048, name: "上海银行" },
        { value: 251, name: "南京银行" },
        { value: 147, name: "光大银行" },
        { value: 102, name: "渣打银行" },
        { value: 310, name: "中原银行" },
        { value: 234, name: "广发银行" },
        { value: 135, name: "摩根银行" }
      ],
      EchartsListdata: [],
      totalStr: "",
      titleText: "",
      screenWidth: ""
    };
  },
  methods: {
    //获取客户 List的方法
    getDate() {
      //获取表格诗句
      // window.console.log(this.formLabelAlign.beginTime)
      if (this.formLabelAlign.endTime) {
        this.formLabelAlign.endTime =
          this.formLabelAlign.endTime + " " + "23:59:59";
      }
      this.$axios
        .get(
          `/spider/statistical/getBankStatistical?beginTime=${
            this.formLabelAlign.beginTime
          }&endTime=${this.formLabelAlign.endTime}&city=${
            this.formLabelAlign.city
          }&userId=${sessionStorage.getItem("id")}`
        )
        .then(res => {
          // console.log(res);
          if (res.data.messageModel.code == 0) {
            this.tableData = res.data.dataModel;
            this.changeEcharts();
          } else {
            this.$message.error(res.data.messageModel.messageText);
            this.tableData = [];
          }
          this.loading = false;
        });
    },
    //清空所有筛选条件的方法
    clearAllCheck() {
      for (let i = 0; i < this.formLabelAlign.length; i++) {
        this.formLabelAlign.formLabelAlign[i] = "";
      }
      this.formLabelAlign.value1 = ""; //未分割的完整版时间区间
    },
    //判断时间区间是否隐藏
    holderQuJian(vId) {
      let obj = {};
      obj = this.timeList.find(item => {
        //这里的fenselectList就是上面遍历的数据源
        return item.id === vId; //筛选出匹配数据
      });
      // console.log(obj.name);
      if (obj.name == "自定义") {
        this.isShow = true;
        this.formLabelAlign.dayType = "customize";
      } else if (obj.name == "昨日") {
        this.value1 = "";
        this.isShow = false;
        // this.formLabelAlign.dayType = "yestoday";
        this.formLabelAlign.beginTime = moment(
          new Date().setTime(new Date().getTime() - 3600 * 1000 * 24 * 1)
        ).format("YYYY-MM-DD");
        this.formLabelAlign.endTime = moment(
          new Date().setTime(new Date().getTime() - 3600 * 1000 * 24 * 1)
        ).format("YYYY-MM-DD");
        // this.formLabelAlign.endTime = moment(new Date()).format("YYYY-MM-DD ");
      } else if (obj.name == "最近七天") {
        this.value1 = "";
        this.isShow = false;
        this.formLabelAlign.beginTime = moment(
          new Date().setTime(new Date().getTime() - 3600 * 1000 * 24 * 7)
        ).format("YYYY-MM-DD");
        this.formLabelAlign.endTime = moment(new Date()).format("YYYY-MM-DD");
      } else if (obj.name == "本月") {
        this.value1 = "";
        this.isShow = false;
        // this.formLabelAlign.dayType = "tomonth";
        this.formLabelAlign.beginTime = moment(new Date()).format("YYYY-MM-01");
        this.formLabelAlign.endTime = moment(new Date()).format("YYYY-MM-DD");
      } else if (obj.name == "上月") {
        this.value1 = "";
        this.formLabelAlign.beginTime = moment()
          .month(moment().month() - 1)
          .startOf("month")
          .format("YYYY-MM-DD");
        this.formLabelAlign.endTime = moment()
          .month(moment().month() - 1)
          .endOf("month")
          .format("YYYY-MM-DD");
        // window.console.log(this.formLabelAlign.beginTime)
        this.isShow = false;
        this.formLabelAlign.dayType = "yesmonth";
      } else if (obj.name == "今日") {
        this.value1 = "";
        this.isShow = false;
        // this.formLabelAlign.dayType = "today";
        this.formLabelAlign.beginTime = moment(new Date()).format("YYYY-MM-DD");
        this.formLabelAlign.endTime = moment(new Date()).format("YYYY-MM-DD");
      } else {
        this.isShow = false;
        this.formLabelAlign.beginTime = "";
        this.formLabelAlign.endTime = "";
        this.formLabelAlign.dayType = "all";
      }
      // window.console.log(this.formLabelAlign.beginTime);
      // window.console.log(this.formLabelAlign.endTime);
      // window.console.log(this.formLabelAlign.dayType);
    },
    //将按钮禁用两秒
    disButton() {
      this.disTBN = true;
      setTimeout(() => {
        this.disTBN = false;
      }, 2000);
    },
    //分页的方法
    // handleSizeChangehandleSizeChange(val) {
    //   this.loading = true
    //   // console.log(val);
    //   if (this.pageConfig.currentPage != 1) {
    //     this.pageConfig.currentPage = 1;
    //     this.pageConfig.pageSize = val;
    //     this.getDate()
    //   }else{
    //     this.pageConfig.pageSize = val;
    //     this.getDate();
    //   }
    // },
    // handleCurrentChange(val) {
    //   this.loading = true
    //   this.pageConfig.currentPage = val;
    //   this.getDate()
    // },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    //查询
    checkCus() {
      this.disButton();
      this.loading = true;
      // if (this.currentUser.currentcity == null) {
      //   if (this.ShowCity == true && this.formLabelAlign.city == "") {
      //     this.$message.error("请选择城市");
      //     return false;
      //   }
      if (this.value1 != "" || this.formLabelAlign.dayType == "customize") {
        this.formLabelAlign.beginTime = this.value1[0];
        this.formLabelAlign.endTime = this.value1[1];
      }

      // } else {
      //   this.formLabelAlign.beginTime = "";
      //   this.formLabelAlign.endTime = "";
      // }
      // if (this.formLabelAlign.beginTime == this.formLabelAlign.endTime && this.formLabelAlign.dayType != "all") {
      //   this.formLabelAlign.beginTime =
      //     this.formLabelAlign.beginTime + " " + "00:00:00";
      //   this.formLabelAlign.endTime =
      //     this.formLabelAlign.endTime + " " + "23:59:59";
      // }
      this.getDate();
      // }
    },
    drawPie(id) {
      window.console.log(document.getElementById(id))
      if(!document.getElementById(id)) return //假如不存在直接返回
      this.charts = echarts.init(document.getElementById(id));
      this.charts.setOption({
        title: {
          // text: [this.wliuyiwei(this.totalStr), "{name|总计}"].join("\n"),
          text: this.titleText,
          // fontSize:"50",
          top: "center",
          left: "center",
          // textAlign: 'center',
          textStyle: {
            rich: {
              value: {
                color: "#303133",
                fontSize: 45,
                fontWeight: "bold",
                lineHeight: 60
              },
              name: {
                color: "#909399",
                lineHeight: 20,
                fontSize: 30
              }
            }
          }
        },
        tooltip: {
          // show: true,
          trigger: "item",
          formatter: "{a} <br/>{b}: {c} ({d}%)"
          // position: ['50%', '50%'],
        },
        series: [
          {
            name: this.formLabelAlign.Dimension,
            type: "pie",
            radius: ["80%", "55%"],
            minAngle: 5,
            avoidLabelOverlap: true,
            labelLine: {
              normal: {
                length: 100,
                length2: 100
              }
            },
            emphasis: {
              label: {
                // show: true,
                fontSize: "30",
                fontWeight: "900",
                position: "center"
              }
            },
            label: {
              normal: {
                formatter: "{a|{a}}{abg|}\n{hr|}\n  {b|{b}：}{c}  {per|{d}%}  ",
                backgroundColor: "#eee",
                borderColor: "#aaa",
                borderWidth: 1,
                borderRadius: 4,
                // shadowBlur:3,
                // shadowOffsetX: 2,
                // shadowOffsetY: 2,
                // shadowColor: '#999',
                // padding: [0, 7],

                rich: {
                  a: {
                    color: "#999",
                    lineHeight: 22,
                    align: "center"
                  },
                  abg: {
                    // backgroundColor: '#333',
                    // width: '100%',
                    // align: 'right',
                    // height: 22,
                    // borderRadius: [4, 4, 0, 0]
                  },
                  hr: {
                    borderColor: "#aaa",
                    width: "100%",
                    borderWidth: 0.5,
                    height: 0
                  },
                  b: {
                    fontSize: 16,
                    lineHeight: 33
                  },
                  per: {
                    color: "#eee",
                    backgroundColor: "#334455",
                    padding: [2, 4],
                    borderRadius: 2
                  }
                }
              }
            },
            data: this.EchartsListdata
          }
        ]
      });
      this.charts.resize();
    },
    changeEcharts(attr) {
      this.EchartsListdata = JSON.parse(
        JSON.stringify(this.initEchartListdata)
      );

      if (this.tableData.length < 3) {
        // this.drawPie("main");
        this.isShowEchart = false;
        return;
      } else {
        this.isShowEchart = true;
      }

      if (!attr) {
        this.titleText = [
          this.wliuyiwei(this.tableData[0]["fangKuangRate"]),
          "{name|总计}"
        ].join("\n");
        attr = "fangKuangRate";
      }

      const newArr = this.tableData;
      // window.console.log(newArr);

      let len = newArr.length;

      if (len > 11) {
        len = 11;
        this.EchartsListdata.length = len;
      } else {
        this.EchartsListdata.length = len - 1;
      }
      // window.console.log(len);

      // window.console.log(this.EchartsListdata);
      newArr.sort((a, b) => {
        return b[attr] - a[attr];
      });

      let total = newArr[0][attr];
      let sum = 0;
      for (let i = 1; i < len; i++) {
        // window.console.log(newArr[i].bankName);
        this.EchartsListdata[i - 1].name = newArr[i]["bankName"];
        this.EchartsListdata[i - 1].value = newArr[i][attr];
        sum += newArr[i][attr];
      }

      if (len >= 11) {
        this.EchartsListdata[len - 1].name = "其他";
        this.EchartsListdata[len - 1].value = total - sum;
      }
      // window.console.log(this.EchartsListdata);
      // this.totalStr = newArr[0][attr].toString();
      // window.console.log(this.totalStr);
      this.$nextTick(() => {
        this.drawPie("main");
      })
    },
    // 改变选项改变标题
    changeDimension() {
      // window.console.log(this.formLabelAlign.Dimension);

      if (this.formLabelAlign.Dimension == "放款额") {
        // console.log(1);
        this.titleText = [
          this.wliuyiwei(this.tableData[0]["fangKuangRate"]),
          "{name|总计}"
        ].join("\n");
        this.changeEcharts("fangKuangRate");
      } else if (this.formLabelAlign.Dimension == "放款笔数") {
        // console.log(2);
        this.titleText = [
          this.wliuyiwei(this.tableData[0]["fangKuanCount"]),
          "{name|总计}"
        ].join("\n");
        this.changeEcharts("fangKuanCount");
      } else {
        this.titleText = [
          this.wliuyiwei(this.tableData[0]["thePayeeRate"]),
          "{name|总计}"
        ].join("\n");
        this.changeEcharts("thePayeeRate");
      }
       this.$nextTick(function() {
      this.drawPie("main");
      // this.changeEcharts();
      // window.console.log(this.tableData);
    });
    },
    //计算标题字符串
    wliuyiwei(value) {
      window.console.log(this.formLabelAlign.Dimension);
      if (value == 0 || value == "0") return "-";
      if (this.formLabelAlign.Dimension == "放款额") {
        let str = Number((parseFloat(value) / 10000).toFixed(1));
        return "{value|￥" + str + "W}";
      } else if (this.formLabelAlign.Dimension == "放款笔数") {
        return "{value|" + value + "笔}";
      } else {
        let str = Number((parseFloat(value) / 10000).toFixed(1));
        return "{value|￥" + str + "W}";
      }
    }
  },
  computed: {
    comDimension() {
      return this.formLabelAlign.Dimension;
    }
  },
  watch: {
    comDimension() {
      this.changeDimension();
      // window.console.log(1);
    }
  },
  // 本地过滤器
  filters: {
    formatTime(value) {
      if (value == null) {
        return "";
      }
      // return moment(value).format("YYYY-MM-DD HH:mm:ss");
      return moment(value).format("YY-MM-DD");
    },
    Proportion(value) {
      if (value == 0 || value == "0") return "-";
      let str = Number((parseFloat(value) * 100).toFixed(2));
      return (str += "%");
      //   var str=Number(point*100).toFixed(1);
      // str+="%";
      // return str;
    }
  },
  created() {
    // this.loading = true;
    // if (window.sessionStorage.getItem("prohibitLogin") == "true") {
    this.currentUser.currentName = window.sessionStorage.getItem("name");
    this.currentUser.currentid = window.sessionStorage.getItem("id");
    this.currentUser.currentLevel = window.sessionStorage.getItem("userLevel");
    this.currentUser.currentcity = window.sessionStorage.getItem(
      "departmentName1"
    );

    if (
      this.currentUser.currentLevel == 0 &&
      this.currentUser.currentcity == "null"
    ) {
      // this.formLabelAlign.city = "all";
      this.ShowCity = true;
      this.getDate();
      this.loading = false;
      // 获取所有城市
      this.$axios
        .get(`/spider/department/getAll`)
        .then(res => {
          // console.log(res);
          this.cityselectList = res.data;
          this.loading = false;
        })
        .catch(error => {
          window.console.log(error);
          this.loading = false;
        });
    } else {
      this.formLabelAlign.city = this.currentUser.currentcity;
      this.getDate();
    }
  },
  // methods:{

  // },
  mounted() {
    this.$nextTick(function() {
      // this.drawPie("main");
      // this.changeEcharts();
      // window.console.log(this.tableData);
    });
    this.screenWidth = document.body.clientWidth-210
    window.onresize = () => {
      this.screenWidth = document.body.clientWidth-210;
      this.drawPie("main")
    };
    window.console.log(this.screenWidth)
    // window.console.log(1)
  }
  //抽取到vuex中试一试
  // computed: {
  //   //  Echartsdata(){
  //   //    return this.$store.state.common.Echartsdata;
  //   //  },
  //   //  EchartsListdata(){
  //   //    return this.$store.state.common.EchartsListdata;
  //   //  }
  // }
};
</script>

<style  lang='scss'>
.BankAnalysis-container {
  //echarts的样式
  * {
    // margin: 0;
    // padding: 0;
    list-style: none;
  }

  .el-form-item.BTN {
    /deep/.el-form-item__content {
      margin-left: 20px !important;
    }
  }
  input.el-input__inner {
    width: 170px;
    height: 32px;
    padding-left: 10px;
  }
  //突出隔行的颜色差异
  .el-table {
    font-size: 12px;
    .cell {
      padding-left: 1px;
      padding-right: 1px;
      text-align: center;
    }
    th {
      padding: 0;
    }
    .warning-row {
      background: #fff;
    }
    .success-row {
      background: #d3d3d3;
    }
    td {
      //取消单元格的上下padding
      padding: 0;
      border-bottom: 1px solid rgb(211, 205, 205);
    }
    .el-button--mini {
      border: 0;
      padding: 5px 15px;
      margin: 5px 0;
      background: rgba(255, 255, 255, 0.01);
    }
    .toEdit:hover {
      color: skyblue;
    }
  }
  // 时间分类框样式
  input.el-input__inner#kinds,
  /deep/input.el-input__inner#time {
    // width: 85px;
    padding-left: 7px;
    height: 32px !important;
  }
  // 日期选择器
  daterange.el-input,
  .el-date-editor--daterange.el-input__inner,
  .el-date-editor--timerange.el-input,
  .el-date-editor--timerange.el-input__inner {
    width: 240px;
    height: 36px;
    vertical-align: middle;
    .el-date-editor .el-range__icon {
      line-height: 27px;
    }
    .el-date-editor .el-range-separator {
      width: 5%;
    }
    /deep/.block,
    #block {
      border: none !important;
      /deep/.el-date-editor--daterange {
        width: 240px !important;
      }
    }
  }
  .el-form-item {
    display: inline-block;
    margin: 3px 0 3px 10px;
  }
  .el-form-item:nth-child(n + 6) {
    margin-top: 0;
  }
  .el-select.time {
    margin-left: 20px;
  }
  .el-input--suffix .el-input__inner.fanwei {
    padding-right: 30px;
    width: 30px;
  }
  .filterCondition {
    background-color: #fff;
    margin-bottom: 20px;
  }
  .check {
    margin-left: 22px;
    padding: 8px 20px;
  }
  .ell {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    line-height: 0.9;
  }
  //分页框样式设置（避免页面被覆盖）
  .el-pagination .el-input__inner {
    width: 100px;
  }
  /deep/canvas {
    width: 100%;
  }
}
</style>